//
//  POLinkTextFieldCell.m
//  POBase
//
//  Created by Pieter Omvlee on 6/4/08.
//  Copyright 2008 Bohemian Coding. All rights reserved.
//

#import "CHLinkTextFieldCell.h"

static NSImage *actionImage;

@implementation CHLinkTextFieldCell

- (NSImage *)actionImage
{
  if (!actionImage) {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    actionImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"FCLinkArrow" ofType:@"png"]];
  }
  return actionImage;
}

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
  [super drawWithFrame:cellFrame inView:controlView];
  
  NSString *key = nil;
  NSOutlineView *table = (NSOutlineView *)[self controlView];
  NSUInteger i, count = [[table tableColumns] count];
  for (i = 0; i < count; i++) {
    NSRect r = [table rectOfColumn:i];
    if (NSIntersectsRect(r,cellFrame))
      key = [[[table tableColumns] objectAtIndex:i] identifier];
  }
  
  id obj = [table itemAtRow:[table selectedRow]];
  
  if ([obj respondsToSelector:@selector(representedObject)])
    obj = [obj representedObject];
  BOOL draw = [[table delegate] tableView:table shouldActionImageForObject:obj key:key];
  
  if ([self isHighlighted] && ![[self stringValue] isEqual:@""] && draw) {
    NSImage *img = [self actionImage];
    [img drawInRect:NSMakeRect(NSMaxX(cellFrame)-11,NSMidY(cellFrame)-5,11,10)
           fromRect:NSMakeRect(0,0,[img size].width,[img size].height)
          operation:NSCompositeSourceOver 
           fraction:1.0];
  }
}

- (NSUInteger)hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView
{
  NSUInteger result = [super hitTestForEvent:event inRect:cellFrame ofView:controlView];
  NSPoint mouse     = [controlView convertPoint:[event locationInWindow] fromView:nil];
  
  if ([self isHighlighted] && ![[self stringValue] isEqual:@""]) {
    NSRect r = cellFrame;
    r.origin.x = NSMaxX(r)-12;
    r.size.width = 12;
    if (NSPointInRect(mouse, r))
      result = NSCellHitContentArea;
  } else
    result = NSCellHitNone;
  lastResult = result;
  return result;
}

- (int)hitTestResult
{
  return lastResult;
}

@end

@implementation CHCloseLinkTextFieldCell

- (NSImage *)actionImage
{
  if (!actionImage) {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    actionImage = [[NSImage alloc] initWithContentsOfFile:[bundle pathForResource:@"close" ofType:@"tif"]];
  }
  return actionImage;
}

@end
